import axios from 'axios'
import { getOrigin, hasOwn, isPlainObject, normalizeUrl } from '@web-utils/core'
import { trimEnd } from 'lodash-es'
import store from '@/store'

const { stringToBoolean } = require('@/config/configGenerator')

const origin = getOrigin()

export const server = normalizeUrl(`${origin}${process.env.VUE_APP_PUBLIC_PATH}`)

export const loginPath = 'login'

/**
 * 是否开启互联同步
 * @type {boolean}
 */
export const connectSync = true

export const uploadUrl = process.env.VUE_APP_UPLOAD_URL === '/' ? trimEnd(origin, '/') : process.env.VUE_APP_UPLOAD_URL
export const downloadUrl =
  process.env.VUE_APP_DOWNLOAD_URL === '/' ? trimEnd(origin, '/') : process.env.VUE_APP_DOWNLOAD_URL
export const bizPrefix = process.env.VUE_APP_BIZ_PREFIX
export const tokenInvalidateTips = '会话已失效，请重新登录！'
export const tokenInvalidateMessage = '会话已失效，是否重新登录？'
export const imageUrl = window.imageUrl || process.env.VUE_APP_IMAGE_URL

export const themes = {
  default: {
    name: '默认',
    value: 'default'
  },
  light: {
    name: '纯白',
    value: 'light'
  }
}

export function getConfig() {
  return axios.get(`${server}config.json?ts=${Date.now()}`)
}

export const configMap = {
  offLine: stringToBoolean(process.env.VUE_APP_OFFLINE)
}

const createServices = () => {
  return {
    /**
     * 系统管理服务
     */
    adminService: '/admin/',
    /**
     * 授权服务
     */
    authService: '/auth/',
    /**
     * 代码生成服务
     */
    genService: '/gen/',
    /**
     * 定时任务服务
     */
    jobService: '/job/',
    /**
     * 分布式事务服务
     */
    txService: '/tx/',
    /**
     * 流程服务
     */
    actService: '/act/',
    /**
     * 微信公众号服务
     */
    mpService: '/mp/',
    /**
     * 支付服务
     */
    payService: '/pay/',
    /**
     * 空间服务
     */
    spaceService: '/cloud-asset-biz/',
    /**
     * 资产服务
     */
    assetService: '/cloud-asset-biz/',
    /**
     * 人事服务
     */
    personnelService: '/cloud-personnel-biz/',
    /**
     * 通用服务
     */
    commonService: '/cloud-common-svc-biz/',
    /**
     * 即时通知服务
     */
    imService: '/cloud-im/'
  }
}

export const services = createServices(configMap)

export async function initApp() {
  await store.dispatch('config/init')
  if (process.env.NODE_ENV === 'production') {
    const res = await getConfig()
    const data = res.data
    patch(configMap, data, false)
    patch(services, data, false)
    patch(services, createServices())
  }
}

function patch(target, patch, append = true) {
  if (isPlainObject(patch)) {
    for (const patchKey in patch) {
      if (append) {
        target[patchKey] = patch[patchKey]
      } else {
        if (hasOwn(target, patchKey)) {
          target[patchKey] = patch[patchKey]
        }
      }
    }
  }
  return target
}
